import {
    Button,
    Icon,
    InputNumber,
    message,
    Popover,
    Slider,
    Space,
    Upload,
    Radio,
    Modal,
    Spin,
    imgPreview,
    ImgCrop,
    Empty,
    ImgDefault,
    Checkbox
} from "@bytedance/mona-ui"
import React, { useMemo, useState, useEffect } from "react"
import { DndContext, useSensors, useSensor, MouseSensor } from "@dnd-kit/core";
import { arrayMove, SortableContext, useSortable } from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import DeteilCanvas from '../../../../../componets/DeteilCanvas'
import { upImageItemFunc, getObjectURL, urlToBase64, shuffleArray } from '@contents/jinritemaiCopyGoods/copyDataFomate'
const { AddIcon } = Icon

let openIndex

const DetelesImage = (props) => {
    const { data } = props
    if (!data) return null
    return (<>
        <div className="detileRefos" style={{
            background: '#fff',
            border: '1px solid #dcdde0',
            borderRadius: 4,
            boxSizing: 'border-box',
            flex: '0 0 auto',
            height: 545,
            width: 300

        }}>
            <div className="title" style={{
                color: '#85878a',
                fontSize: 12,
                height: 32,
                lineHeight: '32px',
                padding: '0 12px',
                background: '#f9f9fa'
            }}>详情预览</div>
            <div className="imageList" style={{
                width: '100%',
                height: 'calc(100% - 32px)',
                overflow: 'auto'
            }}>
                {data.map(item => {
                    return <img src={item.url} alt="" style={{
                        width: '100%'
                    }} key={item.id} />
                })}
            </div>
        </div >
    </>)
}
const MoveImageBpx = (props: any) => {
    const {
        imageData,
        removState,
        allList,
        onChange,
        index
    } = props
    if (!imageData) return null

    const { setNodeRef, listeners, transform, transition } = useSortable({ id: imageData.id })

    const styles: any = {
        transform: CSS.Transform.toString(transform),
        transition: transition,
        zIndex: removState && removState === imageData.id ? 10 : 1,
        position: removState && removState === imageData.id ? 'relative' : 'static',
        opacity: removState && removState === imageData.id ? 0.5 : 1,
    }

    return (
        <div className="moverbox" style={styles} ref={setNodeRef} {...listeners}>
            <Spin spinning={imageData.islodin}>
                <div className="seterimage" style={{
                    cursor: 'move'
                }}>
                    <img src={imageData.url} className="couyimage" />
                    <div className="conterItemStatus">
                        <div className="itemcie">
                            <Icon type="SeeIcon" className="setIcon" onClick={() => {
                                imgPreview({
                                    defaultIndex: index,
                                    imgUrl: allList.map((res => res.url)),
                                })
                            }}></Icon>
                        </div>
                        <div className="itemcie">
                            <Icon type="ClipIcon" className="setIcon" onClick={() => {
                                ImgCrop.imgCropModalFun({
                                    image: imageData?.url,
                                    modalProps: {
                                        onOk: (e, newfile) => {
                                            console.log(e, newfile)
                                            const imageUrl = getObjectURL(newfile)
                                            allList[index].url = imageUrl
                                            allList[index].islodin = true
                                            allList[index].isNewImage = true
                                            allList[index].upStatus = false
                                            onChange && onChange([...allList])
                                            urlToBase64(imageUrl).then(resUrl => {
                                                upImageItemFunc(resUrl).then((upImages) => {
                                                    allList[index].url = upImages.data[0]
                                                    allList[index].islodin = false
                                                    allList[index].isNewImage = true
                                                    allList[index].upStatus = true
                                                    onChange && onChange([...allList])
                                                })
                                            })
                                        },
                                    },
                                });
                            }}></Icon>
                        </div>
                        <div className="itemcie">
                            <Icon type="DeleteIcon" className="setIcon" onClick={() => {
                                allList.splice(index, 1)
                                allList.forEach((res, index) => {
                                    res.id = index + 1
                                })
                                onChange && onChange([...allList])
                            }}></Icon>
                        </div>
                    </div>
                </div>
            </Spin>

        </div>
    )
}
const RomoItemBox = (props: any) => {
    const { data, onChange } = props
    const [list, setList] = useState<any[]>(data)
    useEffect(() => {
        if (data !== list) {
            onChange && onChange(list)
        }
    }, [list])
    useMemo(() => {
        setList(data)
    }, [data])
    const [removState, setRemoveState] = useState(false)
    const sensors = useSensors(
        useSensor(MouseSensor, {
            activationConstraint: {
                distance: 5, // 按住不动移动5px 时 才进行拖拽, 这样就可以触发点击事件
            },
        })
    )
    return <DndContext
        sensors={sensors}
        onDragStart={(e: any) => {
            const { active } = e
            setRemoveState(active.id)
        }}
        onDragEnd={(e) => {
            setRemoveState(false)
            const { active, over } = e
            if (!over || !over.id) return
            let activeIndex
            let overIndex
            list.forEach((val, index) => {
                if (val.id === active.id) {
                    activeIndex = index
                }
                if (val.id === over.id) {
                    overIndex = index
                }
            })
            setList(items => {
                const adddata = arrayMove(items, activeIndex, overIndex)
                return adddata
            })
        }}>

        <SortableContext items={[...list]}>
            <div className="topmovuerfoter-tower">

                {list.map((res: any, index: number) => {
                    return (

                        <MoveImageBpx
                            key={res.id}
                            imageData={res}
                            removState={removState}
                            allList={list}
                            onChange={setList}
                            index={index}
                        />)
                })}
            </div>

        </SortableContext>
    </DndContext>
}
const DetailContent = (props) => {
    const { picImages, searchWord = [], onChange, aiNewObject, getAiImageLodinStatus } = props
    if (!picImages) return
    // console.log('picImages', picImages)
    const [canvasStatus, setCanvasStatus] = useState(false)
    const [showAiDeteailListModeal, setShowAiDeteailListModeal] = useState(false)
    const [addAllTextImageConfigs, setAddAllTextImageConfigs] = useState<any>({})
    const [addTextUrls, setAddTextUrls] = useState('')
    const [picDataImage, setPicDataImage] = useState<any>(null)
    const [getAiImageStatus, setAiImageStatus] = useState(false)
    const [selectAiImage, setSelectAiImage] = useState<any>(null)

    useMemo(() => {
        if (picImages) {
            setPicDataImage(picImages)
        }
    }, [picImages])
    useEffect(() => {
        if (picImages !== picDataImage) {
            onChange(picDataImage)
        }
        // onChange && onChange(picDataImage)
        // console.log('picDataImage', picDataImage)
    }, [picDataImage])
    if (!picDataImage) {
        return
    }

    return <>
        <div className="imsgecontenbo" style={{
            width: '100%',
            padding: 0,
            margin: 0,
        }}>
            <Space size={20} align="start" style={{
                width: '100%',
            }}>
                <DetelesImage data={picDataImage.list}></DetelesImage>
                <Space direction="vertical" size={75}>
                    <div className="imageMoveBox topconter" style={{
                        width: '690px',
                    }}>
                        <RomoItemBox
                            data={picDataImage.list}
                            onChange={(data) => {
                                picDataImage.list = data
                                setPicDataImage({ ...picDataImage })
                            }}
                        />
                    </div>
                    <div className="imageMoveBox" style={{
                        width: '690px',
                    }}>
                        <Space>
                            <Upload
                                btnText={`上传详情图`}
                                btnType="default"
                                btnIcon={<AddIcon />}
                                maxCount={1}
                                showUploadList={false}
                                beforeUpload={(file) => {
                                    const fileType = /\image\/\/*/
                                    if (fileType.test(file.type)) {
                                        const imageUrl = getObjectURL(file)
                                        let upTiemImaghId = picDataImage.list.length + 1
                                        urlToBase64(imageUrl).then(resUrl => {
                                            upImageItemFunc(resUrl).then((upImages) => {
                                                const itemtser = picDataImage.list.find((item) => item.id == upTiemImaghId)
                                                itemtser.url = upImages.data[0]
                                                itemtser.islodin = false
                                                itemtser.upStatus = true
                                                setPicDataImage({ ...picDataImage })
                                                // setPicImageList([...picImageList])
                                            })
                                        })

                                        // 走一个上传
                                        picDataImage.list.push({
                                            id: upTiemImaghId,
                                            url: imageUrl,
                                            islodin: true,
                                            isNewImage: true,
                                            upStatus: false
                                        })
                                        setPicDataImage({ ...picDataImage })
                                        // setPicImageList([...picImageList])
                                        return
                                    }
                                    message.error("仅支持图片")
                                }}
                            />
                            <Button onClick={() => {
                                openIndex = 0
                                setCanvasStatus(true)
                            }}>添加文字</Button>
                            <Button onClick={() => {

                                openIndex = 0
                                setShowAiDeteailListModeal(true)
                            }}>添加AI生成图片</Button>
                            <Button onClick={() => {
                                // setSeletImageIndex()
                                // openIndex = indexbser
                                // setShowAiDeteailListModeal(true)
                                // console.time('开始1')
                                // console.log(' picImages.list ', picDataImage.list)
                                picDataImage.list = shuffleArray(picDataImage.list)
                                // console.log('打乱结果', picImageList)
                                // setPicImageList([...picImageList])
                                // console.timeEnd('开始1')
                                setPicDataImage({ ...picDataImage })
                            }}>打乱详情图</Button>
                        </Space>
                    </div>
                </Space>
            </Space>
        </div>

        <Modal
            visible={canvasStatus}
            onOk={() => {
                if (openIndex === 'ALL') {
                    addAllTextImageConfigs.forEach((itemImage, indexImage) => {
                        if (itemImage.betUrl) {
                            let upTiemImaghId = picDataImage.list.length + 1

                            upImageItemFunc(itemImage.betUrl).then((upImages) => {
                                const itemtser = picDataImage.list.find((item) => item.id == upTiemImaghId)
                                itemtser.url = upImages.data[0]
                                itemtser.islodin = false
                                itemtser.upStatus = true
                                setPicDataImage({ ...picDataImage })
                            })

                            picDataImage.list.push({
                                id: upTiemImaghId,
                                url: itemImage.betUrl,
                                islodin: true,
                                isNewImage: true,
                                upStatus: false
                            })
                            setPicDataImage({ ...picDataImage })
                        }
                    })
                    setCanvasStatus(false)
                    return
                }
                if (addTextUrls) {
                    let upTiemImaghId = picDataImage.list.length + 1
                    upImageItemFunc(addTextUrls).then((upImages) => {
                        const itemtser = picDataImage.list.find((item) => item.id == upTiemImaghId)
                        itemtser.url = upImages.data[0]
                        itemtser.islodin = false
                        itemtser.upStatus = true
                        setPicDataImage({ ...picDataImage })
                    })
                    console.log('upTiemImaghId', upTiemImaghId)
                    picDataImage.list.push({
                        id: upTiemImaghId,
                        url: addTextUrls,
                        islodin: true,
                        isNewImage: true,
                        upStatus: false
                    })
                    setPicDataImage({ ...picDataImage })
                }
                setCanvasStatus(false)
            }}
            onCancel={() => setCanvasStatus(false)}
            title='添加详情文字'
            width={1000}
            bodyStyle={{
                padding: 0,
            }}
            wrapClassName="addBodersModal"
            destroyOnClose={true}
        >
            {/* searchWord={searchWord} copynum={copynum} openIndex={openIndex}  */}
            <DeteilCanvas searchWord={searchWord} copynum={1} openIndex={openIndex} onChangeUrl={(e) => {
                setAddTextUrls(e)
            }}
                onChangeUrlAll={(e) => {
                    setAddAllTextImageConfigs(e)
                }}
            />
        </Modal>
        <Modal
            title="AI智能生成"
            visible={showAiDeteailListModeal}
            onOk={() => {
                if (!selectAiImage) return message.error('请选择图片')
                // allList[index].url = selectAiImage
                let upTiemImaghId = picDataImage.list.length + 1
                picDataImage.list.push({
                    id: upTiemImaghId,
                    url: selectAiImage,
                    islodin: false,
                    isNewImage: false,
                    upStatus: true
                })
                setPicDataImage({ ...picDataImage })
                // onChange && onChange([...allList])
                setShowAiDeteailListModeal(false)

            }}
            onCancel={() => setShowAiDeteailListModeal(false)}
            width={740}
        >
            <Spin spinning={getAiImageLodinStatus} tip="正在AI生成图片， 请稍后">
                <div className="bu" style={{
                    minHeight: 200
                }}>
                    <Button type="link" onClick={() => {
                        if (aiNewObject && aiNewObject.run) {
                            aiNewObject.run()
                        }
                    }} style={{
                        marginBottom: 10,
                        // width: '100%',
                    }}>继续生成</Button>
                    <Space wrap size={15} style={{
                        marginBottom: 0,
                        width: '100%',
                    }}>
                        {aiNewObject?.run_end_images?.map((item, index) => {
                            return <div className="tuerConters" onClick={() => {
                                setSelectAiImage(item)
                            }}>
                                <ImgDefault imgSrc={item} style={{ width: 120, height: 120, margin: "0 auto 10px" }} key={index}></ImgDefault>
                                {selectAiImage == item && <div className="selectTiter">
                                    <Checkbox checked={true} />
                                </div>}
                            </div>
                        })}
                        <Spin spinning={aiNewObject?.run_status == 4} style={{
                            width: 120,
                        }}></Spin>
                    </Space>
                </div>

            </Spin>
        </Modal>
    </>

}

export default DetailContent